package com.buer.controller;

import com.alibaba.fastjson.JSONObject;
import com.buer.dao.constants.BuerCostant;
import com.buer.service.dto.BuerResult;
import com.buer.service.intf.FingerPrintGB1Service;
import com.buer.service.util.IoUtil;
import com.buer.service.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("conf")
public class ConfController {
    /**
     * 日志工具
     */
    private static Logger LOG = LoggerFactory.getLogger(ConfController.class);

    @Autowired
    private FingerPrintGB1Service fingerPrintGB1Service;

    @RequestMapping(value = {"/fingerPrint_GB1"})
    public ModelAndView fingerPrintGB1(HttpServletRequest request) {
        try {


            ModelAndView mv = new ModelAndView("conf/fingerPrint_GB1.ftl");
            mv.addObject("fingerPrintGB1Data", BuerCostant.FINGERPRINT_GB1_DATA);
            return mv;

        } catch (Exception e) {
            LOG.error("显示fingerPrint_GB1异常，e={}", e);
            ModelAndView mv = new ModelAndView("error.ftl");
            mv.addObject("activeIndex", "1");
            mv.addObject("activeName", "1");
            return mv;
        }
    }

    @RequestMapping(value = "/editFingerPrintGB1", method = RequestMethod.POST)
    public void editFingerPrintGB1(@RequestBody String requestStr,
                                   HttpServletResponse response) {
        try {
            //从请求里面获取到修改之后的fingerPrintGB1Data
            JSONObject requestJson = JSONObject.parseObject(requestStr);
            String fingerPrintGB1Data = (String) requestJson.get("fingerPrintGB1Data");

            // 保存到文件
            BuerResult buerResult = fingerPrintGB1Service.saveConfStrToFile(fingerPrintGB1Data);

            // 返回客户端
            ResponseUtil.writeJson(response, buerResult);

        } catch (Exception e) {
            LOG.error("异常，e={}", e);
        }
    }

    @RequestMapping(value = "/getFingerPrintGB1", method = RequestMethod.GET)
    public void getFingerPrintGB1( HttpServletResponse response) {
        try {
            String fingerprint_GB1_data = fingerPrintGB1Service.obtainConfFileStr();

            Map<String, String> data = new HashMap<String, String>();
            data.put("fingerPrintGB1Data",fingerprint_GB1_data);
            ResponseUtil.writeJson(response, data);

        } catch (Exception e) {
            LOG.error("异常，e={}", e);
        }
    }
}
